// src/composables/useUserDB.js
import { useIndexedDB } from './useIndexedDB'
import { reactive, ref } from 'vue'

/**
 * 用户数据库操作封装
 */

// 用户数据库配置
const DB_CONFIG = {
  dbName: 'Vue3AppDB',
  version: 1, // 重要：确保版本号高于之前的版本
  stores: {
    users: {
      keyPath: 'id',
      autoIncrement: true,
      indexes: [
        {
          name: 'userName',
          keyPath: 'userName',
          options: { unique: true }
        },
        {
          name: 'email',
          keyPath: 'profile.email',
          options: { unique: true }
        },
        {
          name: 'createdAt',
          keyPath: 'createdAt',
          options: { unique: false }
        }
      ]
    }
  }
}

// 初始化数据库
const {
  isConnected,
  error,
  putData,
  queryByIndex,
  getDataById,
  deleteData,
  clearStore,
  validateDatabaseIntegrity,
  initializeDB // 添加 initializeDB 用于自动恢复
} = useIndexedDB(DB_CONFIG.dbName, DB_CONFIG.version, DB_CONFIG.stores)

// 当前登录用户
const currentUser = ref(null)

// 用户数据操作
export const useUserDB = () => {
  // 创建用户数据结构
  const createUserData = (userName, userInfo = {}) => {
    const now = new Date().toISOString()
    return {
      userName,
      profile: {
        ...userInfo
      },
      settings: {
        theme: 'light',
        notifications: true,
        language: 'zh-CN'
      },
      customData: {},
      optionInfo: {},
      pageColorList: [],
      orderList: [],
      createdAt: now,
      updatedAt: now
    }
  }

  // 登录用户
  const login = async (userName) => {
    if (!userName) return null

    try {
      // 确保数据库完整性
      await validateDatabaseIntegrity()

      const users = await queryByIndex('users', 'userName', userName)

      if (users && users.length > 0) {
        currentUser.value = reactive(users[0])
        console.log(`用户 ${userName} 登录成功`)
        return currentUser.value
      }

      return null
    } catch (err) {
      console.error(`登录失败: ${err.message}`)
      error.value = err
      return null
    }
  }

  // 注册新用户
  const register = async (userName, userInfo = {}) => {
    if (!userName) return null

    try {
      // 确保数据库完整性
      await validateDatabaseIntegrity()

      // 检查用户名是否已存在
      const usersByName = await queryByIndex('users', 'userName', userName)
      if (usersByName && usersByName.length > 0) {
        console.error(`用户 ${userName} 已存在`)
        return null
      }

      // 创建新用户
      const newUser = createUserData(userName, userInfo)
      await putData('users', newUser)

      // 登录新用户
      currentUser.value = reactive(newUser)
      console.log(`用户 ${userName} 注册成功`)
      return currentUser.value
    } catch (err) {
      console.error(`注册失败: ${err.message || ''}`)
      error.value = err

      // 尝试自动恢复
      if (err.message.includes('不存在')) {
        console.log('[IndexedDB] 尝试自动恢复...')
        await initializeDB() // 重新初始化可能修复问题
        return register(userName, userInfo) // 重试注册
      }

      return null
    }
  }

  // 更新用户特定部分（对象类型）
  const updateUserSection = async (userName, section, newData) => {
    try {
      // 确保数据库完整性
      await validateDatabaseIntegrity()

      const users = await queryByIndex('users', 'userName', userName)
      if (!users || users.length === 0) {
        console.error(`用户 ${userName} 不存在`)
        return null
      }

      const user = users[0]

      // 实现深度合并函数
      const deepMerge = (target, source) => {
        if (typeof target !== 'object' || target === null) {
          return source
        }
        if (typeof source !== 'object' || source === null) {
          return target
        }

        if (Array.isArray(target) && Array.isArray(source)) {
          return source.map((item, index) => deepMerge(target[index], item))
        }

        const result = { ...target }
        Object.keys(source).forEach((key) => {
          result[key] = deepMerge(target[key], source[key])
        })
        return result
      }

      // 使用深度合并更新section数据
      const updatedUser = {
        ...user,
        [section]: deepMerge(user[section] || {}, newData),
        updatedAt: new Date().toISOString()
      }

      await putData('users', updatedUser)

      // 更新当前用户
      if (currentUser.value && currentUser.value.userName === userName) {
        currentUser.value = reactive(updatedUser)
      }

      return updatedUser
    } catch (err) {
      console.error(`更新用户${section}失败: ${err.message}`)
      error.value = err
      return null
    }
  }

  // ------------------- 数组更新方法 -------------------

  // 添加元素到数组字段
  const addToArrayField = async (userName, fieldName, newItem) => {
    try {
      // 确保数据库完整性
      await validateDatabaseIntegrity()

      const users = await queryByIndex('users', 'userName', userName)
      if (!users || users.length === 0) {
        console.error(`用户 ${userName} 不存在`)
        return null
      }

      const user = users[0]

      // 确保字段存在且为数组
      if (!Array.isArray(user[fieldName])) {
        user[fieldName] = []
      }

      let newItemArray = Array.isArray(newItem) ? newItem : [newItem]

      const updatedUser = {
        ...user,
        [fieldName]: [...user[fieldName], ...newItemArray],
        updatedAt: new Date().toISOString()
      }

      await putData('users', updatedUser)

      // 更新当前用户
      if (currentUser.value && currentUser.value.userName === userName) {
        currentUser.value = reactive(updatedUser)
      }

      return updatedUser
    } catch (err) {
      console.error(`更新用户数组${fieldName}失败: ${err.message}`)
      error.value = err
      return null
    }
  }

  // 从数组字段中删除元素
  /**
   * 从用户数组的某个字段中移除满足条件的元素
   *
   * @param userName 用户名
   * @param fieldName 字段名
   * @param predicate 条件函数，用于过滤数组中的元素
   * @returns 更新后的用户对象或null
   * @throws 如果数据库完整性验证失败或查询用户失败，会抛出错误
   */
  const removeFromArrayField = async (userName, fieldName, predicate) => {
    try {
      // 确保数据库完整性
      await validateDatabaseIntegrity()

      const users = await queryByIndex('users', 'userName', userName)
      if (!users || users.length === 0) {
        console.error(`用户 ${userName} 不存在`)
        return null
      }

      const user = users[0]

      // 确保字段存在且为数组
      if (!Array.isArray(user[fieldName])) {
        user[fieldName] = []
        return user
      }

      const updatedUser = {
        ...user,
        [fieldName]: user[fieldName].filter(predicate),
        updatedAt: new Date().toISOString()
      }

      await putData('users', updatedUser)

      // 更新当前用户
      if (currentUser.value && currentUser.value.userName === userName) {
        currentUser.value = reactive(updatedUser)
      }

      return updatedUser
    } catch (err) {
      console.error(`更新用户数组${fieldName}失败: ${err.message}`)
      error.value = err
      return null
    }
  }

  // 更新数组字段中的元素
  const updateArrayFieldItem = async (userName, fieldName, predicate, updateFn) => {
    try {
      // 确保数据库完整性
      await validateDatabaseIntegrity()

      const users = await queryByIndex('users', 'userName', userName)
      if (!users || users.length === 0) {
        console.error(`用户 ${userName} 不存在`)
        return null
      }

      const user = users[0]

      // 确保字段存在且为数组
      if (!Array.isArray(user[fieldName])) {
        user[fieldName] = []
        return user
      }

      const updatedUser = {
        ...user,
        [fieldName]: user[fieldName].map((item) => (predicate(item) ? updateFn(item) : item)),
        updatedAt: new Date().toISOString()
      }

      await putData('users', updatedUser)

      // 更新当前用户
      if (currentUser.value && currentUser.value.userName === userName) {
        currentUser.value = reactive(updatedUser)
      }

      return updatedUser
    } catch (err) {
      console.error(`更新用户数组${fieldName}失败: ${err.message}`)
      error.value = err
      return null
    }
  }

  // 替换整个数组字段
  const replaceArrayField = async (userName, fieldName, newArray) => {
    try {
      // 确保数据库完整性
      await validateDatabaseIntegrity()

      const users = await queryByIndex('users', 'userName', userName)
      if (!users || users.length === 0) {
        console.error(`用户 ${userName} 不存在`)
        return null
      }

      const user = users[0]

      const updatedUser = {
        ...user,
        [fieldName]: newArray,
        updatedAt: new Date().toISOString()
      }

      await putData('users', updatedUser)

      // 更新当前用户
      if (currentUser.value && currentUser.value.userName === userName) {
        currentUser.value = reactive(updatedUser)
      }

      return updatedUser
    } catch (err) {
      console.error(`更新用户数组${fieldName}失败: ${err.message}`)
      error.value = err
      return null
    }
  }

  // ------------------- 便捷方法 -------------------

  // 更新用户基础资料
  const updateUserProfile = (userName, profileData) => {
    return updateUserSection(userName, 'profile', profileData)
  }

  // 更新用户设置
  const updateUserSettings = (userName, settingsData) => {
    return updateUserSection(userName, 'settings', settingsData)
  }

  const updateUserOptionInfo = (userName, optionInfo) => {
    return updateUserSection(userName, 'optionInfo', optionInfo)
  }

  // 更新页面颜色列表（数组）
  const addPageColor = (userName, color) => {
    return addToArrayField(userName, 'pageColorList', color)
  }

  const removePageColor = (userName, predicate) => {
    return removeFromArrayField(userName, 'pageColorList', predicate)
  }

  const updatePageColor = (userName, predicate, updateFn) => {
    return updateArrayFieldItem(userName, 'pageColorList', predicate, updateFn)
  }

  const replacePageColorList = (userName, newColors) => {
    return replaceArrayField(userName, 'pageColorList', newColors)
  }

  // 更新订单列表（数组）
  const addOrder = (userName, order) => {
    return addToArrayField(userName, 'orderList', order)
  }

  const removeOrder = (userName, predicate) => {
    return removeFromArrayField(userName, 'orderList', predicate)
  }

  const updateOrder = (userName, predicate, updateFn) => {
    return updateArrayFieldItem(userName, 'orderList', predicate, updateFn)
  }

  const replaceOrderList = (userName, newOrders) => {
    return replaceArrayField(userName, 'orderList', newOrders)
  }

  // 更新用户自定义数据
  const updateUserCustomData = (userName, customData) => {
    return updateUserSection(userName, 'customData', customData)
  }

  // 获取当前登录用户
  const getCurrentUser = () => {
    return currentUser.value
  }

  // 登出用户
  const logout = () => {
    currentUser.value = null
    console.log('用户已登出')
  }

  // 获取所有用户
  const getUsers = async () => {
    try {
      await validateDatabaseIntegrity()
      return await queryByIndex('users', 'createdAt', '*')
    } catch (err) {
      console.error(`获取用户列表失败: ${err.message}`)
      error.value = err
      return []
    }
  }

  return {
    isConnected,
    error,
    login,
    register,
    updateUserProfile,
    updateUserSettings,
    updateUserOptionInfo,
    updateUserCustomData,
    // 页面颜色列表相关方法
    addPageColor,
    removePageColor,
    updatePageColor,
    replacePageColorList,
    // 订单列表相关方法
    addOrder,
    removeOrder,
    updateOrder,
    replaceOrderList,
    deleteUser: (id) => deleteData('users', id),
    getUser: (id) => getDataById('users', id),
    getUsers,
    clearUsers: () => clearStore('users'),
    getUserByName: (userName) => queryByIndex('users', 'userName', userName),
    getUserByEmail: (email) => queryByIndex('users', 'email', email),
    getCurrentUser,
    logout,
    validateDatabase: validateDatabaseIntegrity
  }
}
